'''17-5-2 吃午饭前 qs
        伪造数据库文件
'''
import os
def get_message():
    #获取基本信息
    large_size=int(input('请输入伪造数据项的条数：'))
    forge_file_name=input('请输入文件名')
    file_path=os.getcwd()+'\\'+forge_file_name
    return large_size,forge_file_name,file_path
import random
# ***       ** *            *  * * * **  **  * * *     * * ** * * *1
def generate_number():
    #生成学号
    number=random.randrange(9999)
    return 20140000+number
# ***       ** *            *  * * * **  **  * * *     * * ** * * *2
def ganerete_name():
    #@1 ：完全随机数 （假的明显）生成姓名
    name=''
    count=0
    while count<=2:
        name+=chr(random.randrange(30000,40000))
        count+=1
    return name
def ganerete_name1():
    #@2：姓氏枚举（百家姓） 名字：随机选字（常用字）
    xingshi='赵钱孙李周吴郑王冯陈楚魏蒋沈韩杨张刘金范高马曹邓林狄施白姜黄耿尚邵罗孟杜贾薛史'
    most_use_name='华林梅磊宝晓永荣亚旭伟云娟丽良文艳霞光卫明辉萍生琴军英静宏峰建燕宇君江海俊超洪健志勇刚丹兴国龙成莉瑞红芳亮清兵平敏庆凤松利金立振宁玉涛秀祥美小新佳青爱锋波德学浩东斌雪民珍强鹏婷娜胜杰飞慧兰琳'
    name=''
    name+=random.choice(xingshi)
    name+=random.choice(most_use_name)
    name+=random.choice(most_use_name)
    return name
# ***       ** *            *  * * * **  **  * * *     * * ** * * *3
def genarate_sex():
    #生成性别
    return random.choice('男女')
#******************************************
def generate_old():
    #生成年龄
    return random.randrange(18,26)
def generate_old1(start_year,end_year):
	#给定范围的随机年龄生成
	return random.randrange(start_year,end_year)
#******************************************
def generate_fenshu():
    #伪造各科成绩，假设全部有补考机会
    return random.randrange(36,100)
def generate_fenshu1(a=0,b=100):
    #有区间的正态分布
    pass
def generate_fenshu2(min_score,max_score):
    #给定范围的随机分数生成
    return random.randrange(min_score,max_score)
# ***       ** *            *  * * * **  **  * * *     * * ** * * *4
def generate_address():
    #家庭住址
    #   生成0-30的随机数 
    sheng=['青海','宁夏','海南','香港','澳门','台湾','河北','山东','山西','黑龙江','吉林','辽宁','天津','河南','陕西','甘肃','新疆','西藏','四川','云南','贵州','重庆','湖北','湖南','广西','广东','福建','浙江','上海','北京','安徽','江苏','内蒙古']
    #对应的每个市的地级行政单位
    shi=[['西宁']]
    # @1枚举+随机数（覆盖率高）
    cun=[]#2000个左右村级行政单位 （要不要用枚举）
    #@2 在不完整的数据库中 用随机数选取

    #@3完全虚假的 随机命名 村名（常用字组合，概率组合）
def student_info(data_term):
    #伪造学生信息表
    data_term.append(generate_number())
    data_term.append(ganerete_name1())
    data_term.append(genarate_sex())
    data_term.append(generate_old())
    return data_term
def student_score(data_term):
    #学生成绩表
    data_term.append(generate_number())#既是主键又是外键
    data_term.append(ganerete_name())
    data_term.append(generate_fenshu())
    data_term.append(generate_fenshu())
    data_term.append(generate_fenshu())
    data_term.append(generate_fenshu())
    data_term.append(generate_fenshu())
    return data_term
# ***       ** *            *  * * * **  **  * * *     * * ** * * *5
def list_to_string(list_table):
    #列表转化为字符串（用来改变写入文件的形式）
    str1=''
    for iter in list_table:
        str1=str1+str(iter)+','
    return str1
#***       ** *            *  * * * **  **  * * *     * * ** * * *6
def  forge_data():
    #生成格式化的数据库文件 forge：伪造
    large_size,forge_file_name,file_path=get_message()
    with open(file_path,'w+',encoding='utf-8') as file_to_write:
        count=0
        while count<large_size:
            data_term=[] #存储一条待写入的数据项（记录）放在循环内否则会累加
            #student_info(data_term)
            student_score(data_term)
            file_to_write.write(list_to_string(data_term)+'\n')
            count+=1
# ***       ** *            *  * * * **  **  * * *     * * ** * * *7
if  __name__=='__main__':
    forge_data()
'''
indentationerror(缩进错误): 空格和tab键混用。

'''








#**********************************************
#		有词表分词的方法

def get_sentence(asd,line,tmpsentence):
    start_len=len(line)
    for word in asd:
        if line.startswith(word) :
            tmp=word+'/' 
            # print(tmpsentence,tmp)
            tmpsentence=tmpsentence+tmp
            line=line[len(word):]
            # print(tmpsentence,line)
    if len(line)==start_len:
        #未登录词
        tmpsentence=tmpsentence+'|'+line[0]+'|'
        line =line[1:]
        return tmpsentence,line
    if len(line)>0:
        tmpsentence,line=get_sentence(asd,line,tmpsentence)
    return tmpsentence,line

string_me=['困立即刻出发松岛枫唉去玩儿','松岛枫出发即刻去玩儿困立']
print(len(string_me))
asd=['困立','松岛枫','即刻','出发','去玩儿']
for line in string_me:
        print(line[0],line[:-1])
        tmpsentence=''
        tmpsentence,line=get_sentence(asd,line,tmpsentence)
        print(tmpsentence,line)
print(line,'over！')










'''
	巴塞尔问题：
		1+1/4+1/9+1/16·····=  PI**2/6=1.6644934..
		证明等式
'''
from math import pi
def _sc(count=100000):
	result=0.0
	for i in range(1,count):
		result+=(1.0/(i*i))
	return result
def basel_problem():
	right=(pi**2)/6
	self_compute=_sc()
	print('误差为：',abs(right-self_compute))
	print('right is ',right)
	print('self_compute is ',self_compute)
#basel_problem()







#==============================================
#
#		加密
#
#==============================================

def check_table(alph1,fairtable):
    ''' 使用数值 而非迭代器.单表映射 ：字符-》位置 '''
    x1,y1=0,0;
    while x1<5 :
        while y1<5 :
            if fairtable[x1][y1] ==alph1 :
                return x1,y1;
            y1=y1+1;
        y1=0;
        x1=x1+1;
    
def multi_map_jiami(alph1,alph2,fairtable):   #默认参数alph2 
    '''  多表映射加密.  三个单引号别多打'''
    #先找到position1、position2
    x1,y1=check_table(alph1,fairtable);
    x2,y2=check_table(alph2,fairtable);
    #四种情况判断：
    if y1==y2:      #同列
        x1=(x1+1)%5;
        x2=(x2+1)%5;
        return fairtable[x1][y1],fairtable[x2][y2];
    elif x1==x2 :     #同行
        y1=(y1+1)%5;
        y2=(y2+1)%5;
        return fairtable[x1][y1],fairtable[x2][y2];
    else :          #既不同行也不同列
        return fairtable[x1][y2],fairtable[x2][y1];
    
def multi_map_jiemi(alph1,alph2,fairtable):
    '''  多表映射解密 '''
    #先找到position1、position2
    x1,y1=check_table(alph1,fairtable);
    x2,y2=check_table(alph2,fairtable);
    #四种情况判断：
    if y1==y2 :     #同列
        x1=x1-1;
        x2=x2-1;
        if x1<0 :
            x1=x1+5;
        if x2<0 :
            x2=x2+5;
        return fairtable[x1][y1],fairtable[x2][y2];    
    elif x1==x2 :    #同行
        y1=y1-1;
        y2=y2-1;
        if y1<0 :
            y1=y1+5;
        if y2<0 :
            y2=y2+5;
        return fairtable[x1][y1],fairtable[x2][y2];
    else:
        return fairtable[x1][y2],fairtable[x2][y1];#同行映射
def used_iter(fairtable):
    ''' 练习使用迭代器 '''
    for x1 in fairtable :
        for y1 in x1:
            print(y1,end=" ");
def duobiao(fairtable):
    mingwen=input("请输入明文：多表加密");
    while True:
        if len(mingwen) >= 2:                   #优化?
            #print(mingwen[:2])
            y1=mingwen[0];
            y2=mingwen[1];
            mingwen = mingwen[2:]
            print(multi_map_jiami(y1,y2,fairtable));
            #print(multi_map_jiemi(y1,y2,fairtable));
        else:
            break;

        
def position_to_alph(alph1,miyao=3):
    ''' 单表映射：字符-》字符'''
    fairtable=('a','b','c','d','e','f','g','h','i','j','k'
              ,'l','m','n','o','p','q','r','s','t','u','v'
              ,'w','x','y','z');
    x=0;
    while(x<26): 
        if fairtable[x] == alph1 :
            print(fairtable[(x+miyao)%26],end=" ");
            break;
        x=x+1;
def danbiao():
    mingwen =input("请输入明文：单表加密")
    for x in mingwen :
        position_to_alph(x,4);
def main():
    '''  调试模块时使用 '''
    fairtable=[ ['p','l','a','y','f']
               ,['i','j','r','s','d']
               ,['g','m','c','h','e']
               ,['b','k','n','o','q']
               ,['t','u','v','w','x']];
        #该表可变
    
    danbiao();
    duobiao(fairtable);
    
if __name__=='__main__' :
    main()
    
    
    
    
    
    


'''
    数值所对应的utf-8编码的字符
                琼生
                17-4-17
'''
def view_utf8(max_num,min_num):
    ''' 传入的参数是待输出函数的上下限'''
    outfile=open("int_utf8.txt",'w',encoding='utf-8')
    text='123'
    count_num=min_num
    while count_num<max_num:
        text='0x'+str(format(count_num,'x'))+'\t'+str(count_num)+'\t'+str(format(count_num,'b'))+'\t'+chr(count_num)+'\t\t'
        outfile.writelines(text)
        count_num=count_num+1
        if count_num%10==0:
            outfile.write('\n')
def default():
    max_num=54321
    min_num=0
    view_utf8(max_num,min_num)
def yourchoice():
    firstnum=input('输入最大值: ')
    lastnum=input('输入最小值: ')
    max_num=int(str(firstnum),10)
    min_num=int(str(lastnum),10)
    view_utf8(max_num,min_num)
def main():
    choice=int(input('0:默认，1：手动确定范围：'))
    if choice==0:
        default()
    elif choice==1:
        yourchoice()
    else:
            print('there is no choice of your\'s.')
#汉字范围：u4e00~u9fa5 (19968~40869)  转换方式：int('9fa5',16)








from math import sqrt
from random import random

def montro_calor():
	'''python实现蒙特卡洛算法 计算PI
	'''
	PI_me=0
	in_cyc=0
	sample_num=10000000

	print("开始计算PI值：")
	for _ in range(sample_num):
		X=random()
		Y=random()

		is_in=sqrt(X**2+Y**2)
		#print(X,Y,is_in)
		if is_in < 1.0 :
			in_cyc+=1
	PI_me=(in_cyc/sample_num)*4.0
	print('由m——t方法计算出的PI ：',PI_me)
	#1G  : 3.1415 78632
  
  







'''
	全连接神经网络
	
'''
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

from keras.models import Sequential
from keras.layers import Dense,Activation
from keras.layers import Dropout
from keras.layers import Flatten
from keras.utils import to_categorical
from pickle import load

pickle_file1='rtdata/tdd.bin'

def all_connect_net():
	''' 尝试用dence 进行分类
	'''
	with open(pickle_file1,'rb') as data:
		input_train=load(data)
		output_train=load(data)
		input_test=load(data)
		output_test=load(data)
	size=len(input_train)
	input_train=input_train.reshape(size,30,100)
	size1=len(input_test)
	input_test=input_test.reshape(size1,30,100)
	model=Sequential()
	model.add(Dense(80,input_shape= (30,100) ))
	model.add(Activation("relu") )
	model.add(Dropout(0.4))  #随机失活20%
	model.add(Dense(60))
	model.add(Activation("relu") )
	model.add(Dropout(0.3))
	model.add(Dense(40))
	model.add(Activation("relu") )
	model.add(Dropout(0.2))
	model.add(Dense(20))
	model.add(Activation("relu") )
	model.add(Dropout(0.1) ) 
	model.add(Dense(10) )
	model.add(Activation("relu") )
	model.add(Dropout(0.1) )
	model.add(Flatten() )
	model.add(Dense(4) )
	model.add( Activation('softmax') )
	
	model.compile(loss='categorical_crossentropy',optimizer='sgd', metrics=['categorical_accuracy'])
	model.fit(input_train, output_train, epochs=500, batch_size=32,verbose=2)
	
	model.summary()  #打印模型概况
	score = model.evaluate(input_test, output_test, batch_size=32,verbose=2)
	print('测试损失：',score[0])
	print('测试准确率：',score[1])
	print('evaluate RESULT:',score)
	
all_connect_net()
# 500轮，windows platform，loss ：0.1044 accuracy：0.9694










